package cn.bestick.cblog.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.bestick.cblog.dmo.Category;
import cn.bestick.cblog.dto.ArticleLiteDto;
import cn.bestick.cblog.dto.CategoryDto;
import cn.bestick.cblog.service.ArticleService;
import cn.bestick.cblog.service.CategoryService;
import cn.bestick.cblog.service.impl.ArticleServiceImpl;
import cn.bestick.cblog.service.impl.CategoryServiceImpl;
import cn.bestick.cblog.util.StringUtil;

public class CategoryServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private CategoryService categoryService = new CategoryServiceImpl();
	private ArticleService articleService = new ArticleServiceImpl();

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.service(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.service(request, response);
	}

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String categoryId = request.getParameter("categoryId");
		if (StringUtil.isNotEmpty(categoryId)) {
			this.detail(request, response, Integer.parseInt(categoryId));
		} else {
			this.list(request, response);
		}
	}

	private void list(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<CategoryDto> categories = categoryService.getCategories();
		request.setAttribute("categories", categories);
		request.setAttribute("mainPage", "template/category/list.jsp");
		request.getRequestDispatcher("index.jsp").forward(request, response);
	}

	private void detail(HttpServletRequest request,
			HttpServletResponse response, int categoryId)
			throws ServletException, IOException {
		Category category = categoryService.getCategory(categoryId);
		List<ArticleLiteDto> articles = articleService.getArticlesByCategory(categoryId);
		if (articles.size() == 0) {
			articles = null;
		}
		request.setAttribute("category", category);
		request.setAttribute("articles", articles);
		request.setAttribute("mainPage", "template/category/detail.jsp");
		request.getRequestDispatcher("index.jsp").forward(request, response);
	}
}
